<?php
namespace app\controller\productAnyShoot;

use app\BaseController;
use app\service\TopviewApiService;
use think\App;
use think\facade\Config;
use think\facade\Db;
use app\constant\ProductBackgroundStatus;

class ProductBackground extends BaseController
{
    protected $apiService;

    public function __construct(App $app)
    {
        $this->apiService = new TopviewApiService();
        parent::__construct($app);
    }

    /**
     * 背景模板列表（读取本地表）
     */
    public function templateList()
    {
        try {
            $categoryId = input('categoryId', null);
            $isCustom = input('isCustom', null);
            $pageNo = input('pageNo/d', 1);
            $pageSize = input('pageSize/d', 20);

            // 限制分页大小
            $config = Config::get('topview.product_anyshoot', []);
            $maxPageSize = $config['max_page_size'] ?? 100;
            if ($pageSize > $maxPageSize) {
                $pageSize = $maxPageSize;
            }
            $query = \think\facade\Db::name('product_background_templates');
            if ($categoryId !== null && $categoryId !== '') {
                $query->where('category_id', intval($categoryId));
            }
            if ($isCustom !== null && $isCustom !== '') {
                $query->where('is_custom', filter_var($isCustom, FILTER_VALIDATE_BOOLEAN) ? 1 : 0);
            }
            $total = $query->count();
            $list = $query->order('id', 'desc')->page($pageNo, $pageSize)->select();

            $data = [
                'total' => $total,
                'pageNo' => $pageNo,
                'pageSize' => $pageSize,
                'data' => $list
            ];
            return json(['code' => 200, 'msg' => 'success', 'data' => $data]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => null]);
        }
    }

    /**
     * 一键提交流程：先去背景，再异步提交背景生成
     * 文档：
     * - 去背景 submit: https://s.apifox.cn/e8e2bcff-c3c8-4f04-9b5c-465e985c31bc/api-333058225
     * - 去背景 query:  https://s.apifox.cn/e8e2bcff-c3c8-4f04-9b5c-465e985c31bc/api-333059677
     * - 背景生成 submit: https://s.apifox.cn/e8e2bcff-c3c8-4f04-9b5c-465e985c31bc/api-338339541
     * - 背景生成 query:  https://s.apifox.cn/e8e2bcff-c3c8-4f04-9b5c-465e985c31bc/api-338339643
     */
    public function autoSubmit()
    {
        try {
            $userId = $this->request->user->uid ?? 0;
            $params = input('post.');

            $imageFileId = $params['productImageFileId'] ?? ($params['imageFileId'] ?? '');
            if (empty($imageFileId)) {
                return json(['code' => 400, 'msg' => '缺少必需参数: productImageFileId', 'data' => null]);
            }

            // 1) 去背景提交（不扣积分，参考文档说明）
            $bgSubmit = $this->apiService->submitRemoveBackgroundTask([
                'productImageFileId' => $imageFileId
            ]);
            $bgTaskId = $bgSubmit['result']['taskId'] ?? '';
            if (empty($bgTaskId)) {
                throw new \Exception('去背景提交成功但未返回taskId');
            }

            // 2) 入库到统一任务表，标记为预处理阶段（template_id=background_v2_pre, status=10）
            $generatingCount = intval($params['generatingCount'] ?? 1);
            if ($generatingCount <= 0) { $generatingCount = 1; }

            $taskDbId = Db::name('product_anyshoot_tasks')->insertGetId([
                'user_id' => $userId,
                'task_id' => $bgTaskId, // 先存去背景任务ID
                'template_id' => 'background_v2_pre',
                'product_image_file_id' => $imageFileId,
                'product_mask_file_id' => $params['productMaskFileId'] ?? null,
                'template_image_file_id' => $params['templateImageFileId'] ?? null,
                'template_mask_file_id' => $params['templateMaskFileId'] ?? null,
                'mode' => $params['mode'] ?? 'advanced',
                'generating_count' => $generatingCount,
                'status' => ProductBackgroundStatus::PREPROCESSING,
                'points_consumed' => 0,
                'create_time' => date('Y-m-d H:i:s')
            ]);

            return json([
                'code' => 200,
                'msg' => '去背景任务已提交，待系统自动提交背景生成',
                'data' => [
                    'dbTaskId' => $taskDbId,
                    'bgRemoveTaskId' => $bgTaskId,
                    'status' => ProductBackgroundStatus::PREPROCESSING,
                    'statusText' => ProductBackgroundStatus::getText(ProductBackgroundStatus::PREPROCESSING)
                ]
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => null]);
        }
    }
}


